import storageService from '@/service/storageService';
import userService from '@/service/userService'
// import userService from '@/service/userService';

const userModule = {
  namespaced: true,
  state: {
    token: storageService.get(storageService.USER_TOKEN),
    userInfo: storageService.get(storageService.USER_INFO) ? JSON.parse(storageService.get(storageService.USER_INFO)) : null, //eslint-disable-line
  },

  mutations: {
    SET_TOKEN(state, token) {
      // 更新本地缓存
      storageService.set(storageService.USER_TOKEN, token);
      // 更新state
      state.token = token;
    },
    SET_USERINFO(state, userInfo) {
      // 更新本地缓存
      storageService.set(storageService.USER_INFO, JSON.stringify(userInfo));
      // 更新state
      state.userInfo = userInfo;
    },
  },

  actions: {
    login(context,{phone, password}){
        return new Promise((resolve, reject)=>{
            userService.login({phone, password}).then((res)=>{
                // console.log(res.data)
                context.commit('SET_TOKEN',res.data.data.authorization);
                // this.SET_TOKEN(res.data.data.authorization);
                // storageService.set(storageService.USER_TOKEN, res.data.data.authorization)
                context.commit('SET_USERINFO',res.data.data.user);
                // this.SET_USERINFO(res.data.data.user);
                // storageService.set(storageService.USER_INFO, JSON.stringify(res.data.data.user))
                // this.$router.replace({name:'home'})
            }).catch((err)=>{
                reject(err);
            })
        })
    }
  },
}

export default userModule;